import { showFailToast, showSuccessToast } from 'vant';
import { ref } from 'vue';

import { changePassword } from '../api';
import ChangePassword from '../models/ChangePassword';

const useChangePassword = () => {
  const form = ref({
    validate: () => Promise.resolve(),
  });
  const params = ref<ChangePassword>(new ChangePassword());
  const loadnig = ref(false);
  const handleChange = async () => {
    try {
      loadnig.value = true;
      await form.value.validate();
      if (params.value.passwordsMatch) {
        showFailToast('两次输入的密码不一致');
        return;
      }
      if (params.value.newIsSameToOld) {
        showFailToast('新密码不能与旧密码相同');
        return;
      }
      const { data } = await changePassword(params.value);
      showSuccessToast(data.message || '修改密码成功');
      loadnig.value = false;
    } catch (error) {
      // eslint-disable-next-line no-console
      console.log(error);
    } finally {
      loadnig.value = false;
    }
  };
  return {
    form,
    params,
    handleChange,
    loadnig,
  };
};

export default useChangePassword;
